package day190705;

/**
 * @author LI DUO
 * @version 1.0
 * @date 2019/7/5 下午 01:26
 */
public class Search {
    public int search(int[] nums, int target) {
        if (nums.length <= 0) {
            return -1;
        }
        return binarySearch(nums, target, 0, nums.length - 1);
    }

    private int binarySearch(int[] nums, int target, int left, int right) {
        int mid = left + ((right - left) >> 1);
        if (target < nums[mid]) {
            return binarySearch(nums, target, left, mid - 1);
        } else if (target > nums[mid]) {
            return binarySearch(nums, target, mid + 1, right);
        } else if (target == nums[mid]){
            return mid;
        }
        return mid;
    }

    private int binarySearch2(int[] nums, int target, int left, int right) {
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (target < nums[mid]) {
                right = mid - 1;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                if (target == nums[mid]) {
                    return mid;
                }
            }
        }
        return -1;
    }
}
